﻿using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace RayD.Core
{

    public static partial class Extention
    {
        /// <summary>
        /// 动态排序
        /// </summary>
        /// <param name="Field">字段名</param>
        /// <param name="orderby">排序方式</param>
        /// <returns></returns>
        public static IQueryable<T> OrderBy<T>(this IQueryable<T> query, string Field, string orderby = "asc")
        {
            if (!string.IsNullOrEmpty(Field))
            {
                var propInfo = GetPropertyInfo(typeof(T), Field);
                var expr = GetOrderExpression(typeof(T), propInfo);

                if (!("desc" == orderby))
                {
                    var method = typeof(Queryable).GetMethods().FirstOrDefault(m => m.Name == "OrderBy" && m.GetParameters().Length == 2);
                    var genericMethod = method.MakeGenericMethod(typeof(T), propInfo.PropertyType);
                    return (IQueryable<T>)genericMethod.Invoke(null, new object[] { query, expr });
                }
                else
                {
                    var method = typeof(Queryable).GetMethods().FirstOrDefault(m => m.Name == "OrderByDescending" && m.GetParameters().Length == 2);
                    var genericMethod = method.MakeGenericMethod(typeof(T), propInfo.PropertyType);
                    return (IQueryable<T>)genericMethod.Invoke(null, new object[] { query, expr });
                }
            }
            return query;
        }
        /// <summary>
        /// 获取反射
        /// </summary>
        /// <param name="objType"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        private static PropertyInfo GetPropertyInfo(Type objType, string name)
        {
            var properties = objType.GetProperties();
            var matchedProperty = properties.FirstOrDefault(p => p.Name == name);
            if (matchedProperty == null)
                throw new ArgumentException("name");

            return matchedProperty;
        }
        /// <summary>
        /// 获取生成表达式
        /// </summary>
        /// <param name="objType"></param>
        /// <param name="pi"></param>
        /// <returns></returns>
        private static LambdaExpression GetOrderExpression(Type objType, PropertyInfo pi)
        {
            var paramExpr = Expression.Parameter(objType);
            var propAccess = Expression.PropertyOrField(paramExpr, pi.Name);
            var expr = Expression.Lambda(propAccess, paramExpr);
            return expr;
        }

        /// <summary>
        /// 动态判断字段值是否存在
        /// </summary>
        /// <param name="Field">字段名</param>
        /// <param name="Value">字段值</param>
        /// <returns></returns>
        public static bool Exist<T>(this IQueryable<T> query, string Field, string Value)
        {
            //if (!string.IsNullOrEmpty(Field) && !string.IsNullOrEmpty(Value))
            //{
                //创建一个来源于那个EF表的参数，并命表格的名字
                ParameterExpression parameter = Expression.Parameter(typeof(T));
                //通过上述的参访问变量值对应的字段
                MemberExpression memberDynamic = Expression.PropertyOrField(parameter, Field);
                //把值转为常量表达式
                ConstantExpression constantDynamic = Expression.Constant(Value);
                //生成一段二元表达式
                var expr = Expression.Equal(memberDynamic, Expression.Convert(constantDynamic, memberDynamic.Type));
                //生成lambda表达式
                var lambda = Expression.Lambda<Func<T, bool>>(expr, parameter);
                //查找
                var res = query.FirstOrDefault(lambda.Compile());
                return res != null;
            //}
            //return true;
        }
    }
}
